package com.mccree.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;

/**
 * 客户端handler
 * @author zhabo
 */
public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //使用客户端发送5条数据
        for (int i = 0; i < 5; i++) {
            String message = "不断向前，一直向前！";
            byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
            int length = message.getBytes(StandardCharsets.UTF_8).length;


            //创建协议包对象
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setLength(length);
            messageProtocol.setData(bytes);
            ctx.writeAndFlush(messageProtocol);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        System.out.println("MyClientHandler.channelRead0");
        int length = msg.getLength();
        byte[] data = msg.getData();


        System.out.println("客户端接收到的信息:"+new String(data,StandardCharsets.UTF_8));
        System.out.println("客户端接收到的数据长度:"+length);
        System.out.println("客户端接收的数据量:"+(++this.count));
        System.out.println("\n\n\n-------------------------------");


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常信息:"+cause.getMessage());
    }
}
